package com.ansion.basedb.dao.helper;

import android.content.Intent;
import android.text.TextUtils;

import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.UserLogicDao;
import com.ansion.utils.CocoLocalBroadcastUtil;
import com.ansion.utils.SettingConstants;
import com.ansion.basedb.dao.bean.UserBabaBean;
import com.ansion.basedb.dao.bean.UserConfigBean;
import com.ansion.basedb.dao.impl.UserLogicCachedDaoImpl;
import com.ansion.basedb.dao.model.CurrentUser;
import com.ansion.basedb.dao.model.GroupModel;
import com.ansion.basedb.dao.model.UserModel;
import com.ansion.basedb.notify.UserChangeNotifier;
import com.ansion.constant.BConstant;
import com.ansion.log.VLog;
import com.ansion.string.StringUtils;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.SettingHelper;
import com.ansion.utils.ValueSafeTransfer;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * Created by Andre on 23-12-26.
 */
public class UserHelper {

    private static UserLogicDao userDBDao;

    public static UserLogicDao getUserDBDao() {
        if (userDBDao == null) {
            synchronized (UserLogicDao.class) {
                if (userDBDao == null) {
                    userDBDao = new UserLogicCachedDaoImpl();
                }
            }
        }
        return userDBDao;
    }

    private static final String TAG = "TAG_USER_TABLE";

    public static List<UserModel> loadAll() {
        UserLogicDao userDao = getUserDBDao();
        if (null == userDao) {
            return null;
        } else {
            return userDao.loadAll();
        }
    }



    public static Set<Long> loadAllBabaUids() {
        List<UserModel> users = loadAll();
        Set<Long> uids = new HashSet<Long>();

        if (users == null || users.isEmpty()) {
            return uids;
        }

        for (UserModel userModel : users) {
            uids.add(userModel.getUserId());
        }

        return uids;

    }

    public static boolean isContactUser(String userId) {
        UserModel userModel = getUserModel(ValueSafeTransfer.longValue(userId));
        if (userModel != null) {
            return isContactUser(userModel);
        }
        return false;
    }

    public static boolean isContactUser(UserModel userModel) {
        return !userModel.isOnlyLocal() || userModel.isBabaTeam() || userModel.isSomaNews();
    }


//	public static void updateAutoAcceptFriend(boolean auto_permit) {
//		UserRPCRequestServicelmpl.getInstance().updateAutoAcceptFriend(
//				auto_permit);
//	}


    /**
     * 对于客户端维护的字段的保存调用此方法
     */
    public static void saveUserLocal(UserModel userModel) {
        UserLogicDao userDao = getUserDBDao();
        if (null == userDao) {
            return;
        }
        userDao.saveUserLocal(userModel);
    }


    public static UserModel getUserModel(long uid) {
        CurrentUser currentUser = LoginedUserMgr.getCurrentLoginedUser();
        if (null == currentUser) {
            return null;
        }

        if (uid == currentUser.getUserId()) {
            return currentUser;
        }

        return UserCacheServiceMgr.getUser(uid);
    }


    public static UserModel getUserModelByUcid(String ucid) {
        CurrentUser currentUser = LoginedUserMgr.getCurrentLoginedUser();
        if (null == currentUser) {
            return null;
        }

        if (ucid != null && ucid.equals(currentUser.getUcid())) {
            return currentUser;
        }

        return UserCacheServiceMgr.getUserByUcid(ucid);
    }

    public static CurrentUser getCurrentUser(CurrentUser model,
                                             UserBabaBean userBean) {
        if (model != null && userBean != null) {

            model.setUserId(userBean.getUid());
            model.setUcid(userBean.getUcid());
            model.setLoginId(String.valueOf(userBean.getUid()));
            model.setLoginToken(userBean.token);
            model.setStatus(userBean.status);
            model.setNickName(userBean.getName());
            model.setCountry(userBean.getCountrycode() + "");
            model.setRegionCode(userBean.getRegionCode());
            model.setCountryPhone(userBean.getMobile() + "");
            model.setAvatarUrl(userBean.getAvartar());

            model.setLastDevKey(userBean.getLastDevKey());
            model.setLastDevType(userBean.getLastDevType());

            model.setCreated(userBean.getCreated());
            model.setUpdated(userBean.getUpdated());

            model.setStatus_type(userBean.getWhatsUpType());
            if (userBean.getWhatsUpType() == UserModel.STATUS_TYPE_SYS) {
                model.setNote(userBean.getSysWhatsUpNum() + "");
            } else if (userBean.getWhatsUpType() == UserModel.STATUS_TYPE_CUSTOM) {
                model.setNote(userBean.getCustomWhatsUpContent());
            }
            model.setVip(userBean.isVip);
            model.setBadgeWallet(userBean.isWallet, userBean.walletExpireTime);
            model.setVipExpireDate(userBean.vipExpireDate);
            model.setDeviceId(userBean.getDeviceId());
            model.setShowLandingPage(userBean.getShowLandingPage());
            if (!TextUtils.isEmpty(userBean.email)) {
                model.setEmail(userBean.email);
            }
            UserSyncHelper.modifyCurrentUserIfNeed(model);
        }
        return model;
    }

    public static void modifyAvatar(CurrentUser user, CurrentUser unSyncUser) {
        user.setAvatarUrl(unSyncUser.getAvatarUrl());
    }

    public static void modifyOtherData(CurrentUser user, CurrentUser unSyncUser) {
        user.setStatus_type(unSyncUser.getStatus_type());
        user.setNote(unSyncUser.getNote());
    }


    public static void saveUserConfig(UserConfigBean userConfigBean) {

        if (userConfigBean == null) {
            return;
        }

        if (VLog.OPEN_LOG) {
            VLog.w("TAG_BADGE", "saveUserConfig walletShowType = %d", userConfigBean.walletShowType);
        }

        SettingHelper.savePersonalPrivacy(SettingConstants.CurrentUserSetting.LAST_SEEN_TYPE, userConfigBean.lastSeenPrivacyType);
        SettingHelper.savePersonalPrivacy(SettingConstants.CurrentUserSetting.PROFILE_PHOTO_TYPE, userConfigBean.profilePhotoPrivacyType);
        SettingHelper.savePersonalPrivacy(SettingConstants.CurrentUserSetting.PROFILE_STATUS_TYPE, userConfigBean.profileStatusPrivacyType);
        SettingHelper.savePersonalPrivacy(SettingConstants.CurrentUserSetting.WALLET_BADGE_TYPE, userConfigBean.walletShowType);
        SettingHelper.setNotificationAlert(userConfigBean.alert);
        SettingHelper.setNotificationPreview(userConfigBean.preview);
        SettingHelper.setNotificationVibrate(userConfigBean.vibrate);
        SettingHelper.setNotificationFriendJoin(userConfigBean.enableFriendNotifyOption);
        SettingHelper.saveHaveReadPrivacyType(userConfigBean.haveReadPrivacyType);
        SettingHelper.savePhotoAutoDownloadOption(userConfigBean.photoAutoDownloadOption);
        SettingHelper.saveVideoAutoDownloadOption(userConfigBean.videoAutoDownloadOption);
        SettingHelper.saveOriginalPhtoAutoDownloadOption(userConfigBean.fullImageAutoDownloadOption);
        SettingHelper.saveAutoSaveGalleryOption(userConfigBean.autoSaveGalleryOption == 1);
        GroupHelper.saveFavouriteGroups(userConfigBean.favoriteGroupList);

        CocoLocalBroadcastUtil.sendLocalBroadcast(new Intent(
                        BConstant.FriendAction.ACTION_GETCOCOACCOUNTCONFIG_END),
                BConstant.FriendAction.EXTRA_ERRCODE, BConstant.NetworkCode.OK);

        VLog.i(TAG, "saveUserConfig--" + userConfigBean);
    }

    /***
     * 按道理来讲不应该删除本地，因为每次getUser的时候都会检查本地有没有，本地没有就会向server拉取
     * @param uids
     */
    @Deprecated
    public static void deleteBaba(List<Long> uids) {
        UserLogicDao dao = getUserDBDao();
        if (null != dao) {
            dao.deleteAppUser(uids);
        }
    }

    /*
     *按道理来讲不应该删除本地，因为每次getUser的时候都会检查本地有没有，本地没有就会向server拉取
     */
    @Deprecated
    public static void deleteBaba(long uid) {
        UserLogicDao dao = getUserDBDao();
        if (null != dao) {
            dao.deleteAppUser(uid);
        }
    }

    public static boolean isMatchEnd() {
        UserLogicDao dao = getUserDBDao();
        if (dao == null) {
            return false;
        }
        return dao.isMatchEnd();
    }

    public static void setIsMatchEnd() {
        VLog.i("setIsMatchEnd", "setIsMatchEnd");
        UserLogicDao dao = getUserDBDao();
        if (dao == null) {
            return;
        }
        dao.setIsMatchEnd();
    }


    public static void updateAllSessionGroupMembers(List<Long> sessionGroupIds) {
        if (sessionGroupIds == null || sessionGroupIds.isEmpty()) {
            return;
        }
        Set<Long> groupUids = new HashSet<>();

        for (Long groupId : sessionGroupIds) {
            GroupModel group = GroupHelper.getGroupModel(groupId);
            if (group != null) {
                Set<Long> idSet = group.getUserIdSet();
                if (idSet != null && !idSet.isEmpty()) {
                    groupUids.addAll(idSet);
                }
            }
        }
        if (!groupUids.isEmpty()) {
            List<Long> groupUidLst = new ArrayList<>(groupUids);
//            getSimpleBabaAccountList(groupUidLst);
        }
    }
    /**
     * 根据UCID获取 appuser json
     * @param ucId
     * @return
     */
    public static String getAppUserJsonByUcId(String ucId) {
        try {
            if (TextUtils.isEmpty(ucId)) {
                return null;
            }
            UserModel userModel = getUserModelByUcid(ucId);
            if (userModel == null) {
                return null;
            }
            JSONObject itemObject = getAppUserJsonByUserModel(userModel);
            return itemObject != null ? itemObject.toString() : null;
        } catch (Throwable e) {
            VLog.e("TAG_CONTACT", "getUserModelJson = %s", e.toString());
        }
        return null;
    }

    public static JSONObject getAppUserJsonByUserModel(UserModel userModel) {
        try {
            if (userModel == null) {
                return null;
            }
            JSONObject itemObject = new JSONObject();
            itemObject.put(BConstant.Contact.KEY_USER_ID, userModel.getUserId());
            itemObject.put(BConstant.Contact.KEY_UCID, userModel.getUcid());
            itemObject.put(BConstant.Contact.KEY_MOBILE, userModel.getCountryPhone());
            itemObject.put(BConstant.Contact.KEY_AVATAR, userModel.getAvatarUrl());
            itemObject.put(BConstant.Contact.KEY_AVATAR_DISPLAY_TEXT, userModel.getAvatarDisplayText());
            itemObject.put(BConstant.Contact.KEY_NICKNAME, userModel.getNickName());
            return itemObject;
        } catch (Throwable e) {
            VLog.e("TAG_CONTACT", "getUserModelJson = %s", e.toString());
        }
        return null;
    }
    public static void updateStatus(int statusType, String customStatus,
                                    int sysStatusNum) {
//        UserRPCRequestServicelmpl.getInstance().updateWhatsUp(statusType,
//                customStatus, sysStatusNum);
    }
}
